package com.java.netty.nio.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @Author: Dgg
 * @Date: 2022/1/24 22:08
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
	private int count;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {

		byte[] bytes = new byte[msg.readableBytes()];
		msg.readBytes(bytes);
		//bytes转换字符串
		String s = new String(bytes, CharsetUtil.UTF_8);
		System.out.println("收到客户端数据:" + s);
		System.out.println("服务端接收到消息量" + (++this.count));
		//恢复数据到客户端
		ctx.writeAndFlush(Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
